package com.bigzero.workflow.modules.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.bigzero.workflow.common.exception.WorkflowException;
import com.bigzero.workflow.common.model.R;
import com.bigzero.workflow.modules.system.dto.RoleMenuDto;
import com.bigzero.workflow.modules.system.service.RoleMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 角色菜单关联前端控制器
 * @author fanxinxiong
 * @since 2025-02-11
 */
@RestController
@RequestMapping("/system/roleMenu")
public class RoleMenuController {

    @Resource
    private RoleMenuService roleMenuService;

    /**
     * 保存角色菜单集合表单校验
     * @param roleMenuDto
     */
    public void saveRoleMenusFormValidate(RoleMenuDto roleMenuDto){
        if(StringUtils.isBlank(roleMenuDto.getRoleId())) {
            throw new WorkflowException("失败:角色id不能为空");
        }
    }

    /**
     * 保存角色关联菜单id集合
     * @param roleMenuDto
     */
    @Tag(name = "系统管理-角色管理")
    @Operation(summary = "分配权限-保存", description = "保存角色关联菜单id集合")
    @PreAuthorize("hasAuthority('sys:role:configPerm')")
    @PostMapping(value = "saveRoleMenuIdList")
    public R<String> saveRoleMenuIdList(@RequestBody RoleMenuDto roleMenuDto){
        //保存角色菜单集合校验
        saveRoleMenusFormValidate(roleMenuDto);
        //保存角色菜单集合
        roleMenuService.saveRoleMenuIdList(roleMenuDto);
        return R.ok();
    }

    /**
     * 根据角色id查询菜单id集合
     * @param roleId
     * @return List<Integer>
     */
    @Tag(name = "系统管理-角色管理")
    @Operation(summary = "根据角色id查询菜单id集合", description = "根据角色id查询菜单id集合")
    @Parameters({
            @Parameter(name = "roleId", description = "角色ID", example = "1", required = true)
    })
    @GetMapping(value = "getMenuIdListByRoleId")
    public R<List<String>> getMenuIdListByRoleId(@RequestParam String roleId){
        return R.ok(roleMenuService.getMenuIdListByRoleId(roleId));
    }

    /**
     * 根据角色id查询菜单id集合
     * @param roleId
     * @return List<Integer>
     */
    @Tag(name = "系统管理-角色管理")
    @Operation(summary = "根据角色id查询菜单id集合(层级)", description = "根据角色id查询菜单id集合(层级)")
    @Parameters({
            @Parameter(name = "roleId", description = "角色ID", example = "1", required = true)
    })
    @GetMapping(value = "getLevelMenuIdListByRoleId")
    public JSONObject getLevelMenuIdListByRoleId(@RequestParam String roleId){
        return roleMenuService.getLevelMenuIdListByRoleId(roleId);
    }
}
